import Taro from '@tarojs/taro';
import { request } from './httpRequest';

// 获取STS凭证
const getSTSToken = async () => {
  const res = await request({
    url: '/api/sts',
    method: 'GET'
  });
  return res.data;
};



// 核心上传方法
export const uploadTempToOSS = async (tempPath: string): Promise<string> => {
  try {

    const { accessKeyId, policy, signature, host, region, bucket, xOssSecurityToken, xOssDate, uploadPathTemplate } = await getSTSToken();

    // 生成文件名(使用后端返回的路径模板,更具安全性、一致性)
    const ext = tempPath.split('.').pop() || 'jpg';
    const fileName = `${uploadPathTemplate}.${ext}`;

    // 构造表单数据
    const formData = {
      key: fileName,
      policy,
      OSSAccessKeyId: accessKeyId,
      Signature: signature,
      'x-oss-date': xOssDate,
      'x-oss-security-token': xOssSecurityToken,
      success_action_status: '200'
    };

    console.log(formData, 'formData')

    // 执行上传
    const { statusCode } = await Taro.uploadFile({
      url: host,
      filePath: tempPath,
      name: 'file',
      formData,
    });

    return statusCode === 200
      ? `${host}/${fileName}`
      : Promise.reject('上传失败');

  } catch (error) {
    console.error('OSS上传失败:', error);
    throw new Error('文件上传失败，请重试');
  }
};